package com.cloudfast.manager.impl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import com.cloudfast.config.property.c.LocalProperty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.cloudfast.manager.FileStorageManager;
import com.cloudfast.response.FileResponse;
import com.cloudfast.utils.FileUtils;

/**
 * 本地文件操作
 *
 * @author liuyw
 */
public class LocalStorageManagerImpl extends BaseManagerImpl implements FileStorageManager {

    private LocalProperty storageProperty;

    public LocalStorageManagerImpl(LocalProperty storageProperty, int maxFileSize) {
        this.storageProperty = storageProperty;
        this.maxFileSize = maxFileSize;
    }

    @Override
    public FileResponse upload(MultipartFile file) {
        return upload(file, null);
    }

    @Override
    public FileResponse upload(MultipartFile file, String prefix) {

        // 文件不能为空
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }

        // 不能超过最大支持
        if (file.getSize() > maxFileSize) {
            throw new RuntimeException("文件太大,已超出最大支持范围:" + maxFileSize);
        }
        // 获取文件名称
        String originalName = file.getOriginalFilename();
        // 获取后缀名称
        String suffix = FileUtils.getFilenameSuffix(originalName);
        // 获取需要保存的文件名称
        String radomName = FileUtils.getRadomName() + "." + suffix;

        // 获取文件保存的路径
        String storageFilePath = "/" + FileUtils.getYmdPath() + "/";
        if (StringUtils.isNotEmpty(prefix)) {
            storageFilePath = "/" + prefix + "/" + FileUtils.getYmdPath() + "/";
        }

        FileResponse fileResponse = null;
        try {
            fileResponse = upload(file.getInputStream(), storageFilePath, radomName);
            if (fileResponse != null) {
                fileResponse.setOriginalName(originalName);
                fileResponse.setFileSize(file.getSize());
                fileResponse.setBrowser((this.storageProperty.getBrowserPrefix() + "/" + storageFilePath + radomName)
                        .replaceAll("//", ""));
            }
        } catch (IOException e) {
            throw new RuntimeException("读取文件流失败.");
        }

        return fileResponse;
    }

    @Override
    public FileResponse upload(InputStream stream, String filePath, String fileName) {
        File file = new File(storageProperty.getFileHome() + filePath, fileName);
        File parent = file.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        try (FileOutputStream fos = new FileOutputStream(file);) {
            byte[] b = new byte[1024];
            while ((stream.read(b)) != -1) {
                fos.write(b);// 写入数据
            }
            stream.close();
            fos.flush();
            fos.close();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return new FileResponse("", filePath + fileName, fileName, fileName.split("\\.")[1], file.length(), "");
    }

    @Override
    public byte[] download(String filePath) {
        File file = new File(this.storageProperty.getFileHome() + filePath);
        ByteArrayOutputStream bout = null;
        byte[] data = null;
        if (file.exists()) {
            int len;
            byte[] bs = new byte[1024];
            try (InputStream is = new FileInputStream(file);) {
                bout = new ByteArrayOutputStream();
                while ((len = is.read(bs)) != -1) {
                    bout.write(bs, 0, len);
                }
                // 转成byte字节
                data = bout.toByteArray();
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }
        return data;
    }

    @Override
    public int deleteFile(String filePath) {
        File file = new File(storageProperty.getFileHome() + filePath);
        if (file.exists()) {
            file.deleteOnExit();
            return 1;
        }
        return 0;
    }

    @Override
    public List<File> iterationFile(String rootPath) {
        // TODO Auto-generated method stub
        return null;
    }
}
